<style lang="less" scoped>
  @import './webspider.less';
</style>

<template>
  <div class="layout">
    <Layout :style="{height: '100%'}">
        <Sider
          :style="{height: '100%', left: 0, overflow: 'auto', background: '#FFFFFF'}"
          :width="260"
          :collapsed-width="64"
          hide-trigger>
            <Row :gutter="4">
              <Col span="20">
                <Input v-model="newSpiderConfig.name" placeholder="请输入爬虫配置名"/>
              </Col>
              <Col span="4">
                <Tooltip content="添加配置" placement="bottom-end">
                  <Button class="workspace-manage-btn" @click="addSpiderConfigClickHandle"><Icon type="md-add"></Icon></Button>
                </Tooltip>
              </Col>
            </Row>

            <ul class="menu">
              <li v-for="(item, index) in spiderConfigList" :key="index" @click="selectSpiderConfigClickHandle(index, item)" class="menu-item">
                {{item.name}}
                <Button @click.stop="deleteSpiderConfigClickHandle(index)" style="float: right;" size="small" type="error" ghost>删除</Button>
                <Button style="float: right;" size="small" type="success" ghost>编辑</Button>
              </li>
            </ul>
        </Sider>
        <Content>
          <div class="content">
            <Row style="margin-top: 3px;">
              <Col span="10">
                <Input v-model="selectSpiderConfig.data.name" placeholder="请输入爬虫名称"/>
              </Col>
              <Col span="4">
                <Select v-model="selectSpiderConfig.data['content-type']" placeholder="请选择内容类型" @on-change="contentTypeChangeHandle">
                  <Option value="json">JSON</Option>
                  <Option value="jsonp">JSONP</Option>
                  <Option value="html">HTML</Option>
                </Select>
              </Col>
              <Col span="4">
                <Select v-model="selectSpiderConfig.data['request-method']" placeholder="请选择请求类型" @on-change="contentTypeChangeHandle">
                  <Option value="GET">GET</Option>
                  <Option value="POST">POST</Option>
                </Select>
              </Col>
              <Col span="2" style="line-height: 30px; text-align: center;">
                <i-switch :value="selectSpiderConfig.data.enabled === 1" @on-change="enabledChangeHandle"></i-switch>
              </Col>
              <Col span="4" class="top-operation-area">
                <Button v-if="!isSpiderRuning" type="info" ghost class="top-btn" @click="scriptSpiderClickHandle">执行爬虫</Button>
                <Button v-else type="success" ghost class="top-btn">爬虫执行中...</Button>
                <Button type="info" ghost class="top-btn" @click="downSpiderResultClickHandle">下载结果</Button>
              </Col>
            </Row>
            <Row type="flex" justify="center" align="middle" style="margin-top: 3px;">
              <Col span="4">
                <Input v-model="selectSpiderConfig.data['save-folder']" placeholder="请输入保存地址" type="textarea" :rows="3" size="small"/>
              </Col>
              <Col span="16">
                <Input v-model="selectSpiderConfig.data.baseUrl" placeholder="爬虫基础地址" type="textarea" :rows="3" size="small"/>
              </Col>
              <Col span="2">
                <Input v-model="selectSpiderConfig.data.pageNumStart" placeholder="开始页码"/>
                <Input v-model="selectSpiderConfig.data.pageSize" placeholder="每页条数" style="margin-top: 3px;"/>
              </Col>
              <Col span="2">
                <Input v-model="selectSpiderConfig.data.pageNumEnd" placeholder="结束页码"/>
                <Input v-model="selectSpiderConfig.data.sleepTime" placeholder="休眠时间（毫秒）" style="margin-top: 3px;"/>
              </Col>
            </Row>
            <Row type="flex" justify="center" align="middle" style="margin-top: 3px;">
              <Col span="24">
                <Input v-model="selectSpiderConfig.data['request-header']" placeholder="请输入请求头" type="textarea" :rows="3" size="small"/>
              </Col>
            </Row>
            <Row style="margin-top: 3px;">
              <Col span="24">
                <span>获取爬虫URL集</span>
              </Col>
            </Row>
            <spider-html-urlconfig v-if="selectSpiderConfig.data['content-type']=='html'" v-model="selectSpiderConfig.data['parse-rules']"></spider-html-urlconfig>
            <spider-urlconfig v-else v-model="selectSpiderConfig.data['parse-rules']"></spider-urlconfig>
            <Row style="margin-top: 3px;">
              <Col span="24">
                <span>获取网页内容</span>
              </Col>
            </Row>
            <Row type="flex" justify="center" align="middle" style="margin-top: 3px;">
              <Col span="24">
                <Input v-model="selectSpiderConfig.data['node-url-handle']" placeholder="节点域名特殊处理"/>
              </Col>
            </Row>
            <spider-contentconfig v-model="selectSpiderConfig.data['parse-result']"></spider-contentconfig>

            <Button type="success" style="width: 100%; margin: 4px 0px;" ghost @click="saveSpiderConfigClickHandle" >保存爬虫配置</Button>
            <vue-json-editor v-model="selectSpiderConfig.data" :showBtns="false" :mode="'code'" lang="zh" />
            <Button type="success" style="width: 100%; margin: 4px 0px;" ghost @click="saveSpiderConfigClickHandle" >保存爬虫配置</Button>
          </div>
        </Content>
    </Layout>
  </div>
</template>

<script>
import baseURL from '_conf/url'
import vueJsonEditor from 'vue-json-editor'
import { SpiderUrlconfig, SpiderContentconfig, SpiderHtmlUrlconfig } from '_c/spider'
import { listSpiderConfig, addSpiderConfig, deleteSpiderConfig,
  saveSpiderConfig, scriptWebSpider, isSpiderRuning } from '@/api/webspider'

export default {
  components: {
    vueJsonEditor,
    SpiderUrlconfig,
    SpiderContentconfig,
    SpiderHtmlUrlconfig
  },
  data () {
    return {
      getSpiderDownloadDataUrl: baseURL + '/script-web-spiders/',
      spiderConfigList: [],
      newSpiderConfig: {},
      selectSpiderConfig: {
        data: {}
      },
      isSpiderRuning: false,
      setTimeoutId: null
    }
  },
  mounted () {
  },
  activated () {
    this.init()
  },
  deactivated () {
  },
  methods: {
    init () {
      this.loadSpiderConfig()
    },
    loadSpiderConfig () {
      listSpiderConfig().then(res => {
        this.spiderConfigList = res
      })
    },
    addSpiderConfigClickHandle () {
      if (!this.newSpiderConfig.name) {
        this.$Message.error('爬虫配置名不能为空')
        return
      }

      addSpiderConfig(this.newSpiderConfig).then(res => {
        if (this.newSpiderConfig.name !== res) {
          this.$Message.error(res)
          return
        }
        this.loadSpiderConfig()
      })
    },
    deleteSpiderConfigClickHandle (id) {
      deleteSpiderConfig(id).then(res => {
        if (id !== res) {
          this.$Message.error(res)
          return
        }
        this.loadSpiderConfig()
      })
    },
    selectSpiderConfigClickHandle (id, config) {
      clearTimeout(this.setTimeoutId)
      this.checkSpiderRuning(config['save-folder'])

      if (!config['parse-rules']) {
        this.$set(config, 'parse-rules', {})
      }
      if (!config['parse-result']) {
        this.$set(config, 'parse-result', {})
      }

      this.$set(this.selectSpiderConfig, 'id', id)
      this.$set(this.selectSpiderConfig, 'data', config)
    },
    saveSpiderConfigClickHandle () {
      if (!(this.selectSpiderConfig.id || this.selectSpiderConfig.id === 0)) {
        this.$Message.error('请先选择爬虫配置')
        return
      }
      saveSpiderConfig(this.selectSpiderConfig.id, this.selectSpiderConfig.data).then(res => {
        if (this.selectSpiderConfig.id === res) {
          this.$Message.success('保存成功')
        } else {
          this.$Message.error(res)
        }
      })
    },
    enabledChangeHandle (value) {
      this.$set(this.selectSpiderConfig.data, 'enabled', value ? 1 : 0)
    },
    scriptSpiderClickHandle () {
      if (!(this.selectSpiderConfig.id || this.selectSpiderConfig.id === 0)) {
        this.$Message.error('请先选择爬虫配置')
        return
      }
      scriptWebSpider(this.selectSpiderConfig.data).then(res => {
        if (this.selectSpiderConfig.data['save-folder'] === res) {
          this.$Message.success('执行成功')
          this.checkSpiderRuning(res)
        } else {
          this.$Message.error(res)
        }
      })
    },
    downSpiderResultClickHandle () {
      if (!(this.selectSpiderConfig.id || this.selectSpiderConfig.id === 0)) {
        this.$Message.error('请先选择爬虫配置')
        return
      }
      /*
      getWebSpiderResult(btoa(encodeURI(this.selectSpiderConfig.data['save-folder']))).then(blob => {
        let filename = '爬虫执行结果.zip'
        if (window.navigator.msSaveOrOpenBlob) {
          navigator.msSaveBlob(blob, filename)
        } else {
          let link = document.createElement('a')
          link.style.display = 'none'
          link.download = filename
          link.href = window.URL.createObjectURL(new Blob([blob]))
          link.click()
          window.URL.revokeObjectURL(link.href)
        }
      })
       */
      open(this.getSpiderDownloadDataUrl + btoa(encodeURI(this.selectSpiderConfig.data['save-folder'])) + '/')
    },
    checkSpiderRuning (saveFolder) {
      isSpiderRuning(btoa(encodeURI(saveFolder))).then(res => {
        this.isSpiderRuning = res
        clearTimeout(this.setTimeoutId)
        if (res === true) {
          this.setTimeoutId = setTimeout(this.checkSpiderRuning, 1000, saveFolder)
        }
      })
    },
    contentTypeChangeHandle (value) {
      if (value === 'html') {
        this.$set(this.selectSpiderConfig.data['parse-rules'], 'url', {})
        this.$set(this.selectSpiderConfig.data['parse-rules'], 'title', {})
        this.$set(this.selectSpiderConfig.data['parse-rules'], 'primary-key', {})
      } else {
        delete this.selectSpiderConfig.data['parse-rules']['url']
        delete this.selectSpiderConfig.data['parse-rules']['title']
        delete this.selectSpiderConfig.data['parse-rules']['primary-key']
      }
    }
  }
}
</script>

<style lang="less" scoped>
  .layout{
    background: #f5f7f9;
    position: relative;
    border-radius: 4px;
    overflow: hidden;
    height: 100%;

    /deep/ .workspace-manage-btn{
        padding: 5px 10px 6px;
    }

    .menu {
      .menu-item {
        border-bottom: 1px solid #eeeeee;
        padding: 6px 8px;
        line-height: 21px;
        font-size: 14px;
      }
      .menu-item:hover {
        color: #4466dd;
        cursor: pointer;
      }
    }

    /deep/ .ivu-btn-small{
        padding: 0px 4px;
        font-size: 12px;
    }

    /deep/ .ivu-table-small{
        .ivu-table-title{
            height: 38px;
            line-height: 38px;
        }
        .ivu-table-footer{
            height: 40px;
            line-height: 39px;
        }
    }

    .top-operation-area {
      display: flex;
      justify-content: space-around;
    }

    .top-btn {
      margin-left: 1px;
      width: 100%;
      display: inline-grid;
      span {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        display: inline-block;
        width: 100%;
      }
    }

    /deep/ .content{
        height: 100%;
        background: #FFFFFF;
        border-left: 1px solid #eeeeee;
    }

    /deep/ .jsoneditor-vue {
        height: 460px;
    }
  }
</style>
